/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.modules.system.domain.UserAccount;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.UserAccountRepository;
import me.zhengjie.modules.system.service.UserAccountService;
import me.zhengjie.modules.system.service.dto.UserAccountDto;
import me.zhengjie.modules.system.service.dto.UserAccountQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.UserAccountMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wangyu
* @date 2024-03-20
**/
@Service
@RequiredArgsConstructor
public class UserAccountServiceImpl implements UserAccountService {

    private final UserAccountRepository userAccountRepository;
    private final UserAccountMapper userAccountMapper;

    @Override
    public Map<String,Object> queryAll(UserAccountQueryCriteria criteria, Pageable pageable){
        Page<UserAccount> page = userAccountRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(userAccountMapper::toDto));
    }

    @Override
    public List<UserAccountDto> queryAll(UserAccountQueryCriteria criteria){
        return userAccountMapper.toDto(userAccountRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public UserAccountDto findById(Long acctId) {
        UserAccount userAccount = userAccountRepository.findById(acctId).orElseGet(UserAccount::new);
        ValidationUtil.isNull(userAccount.getAcctId(),"UserAccount","acctId",acctId);
        return userAccountMapper.toDto(userAccount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAccountDto create(UserAccount resources) {
        if(userAccountRepository.findByAcctCode(resources.getAcctCode()) != null){
            throw new EntityExistException(UserAccount.class,"acct_code",resources.getAcctCode());
        }
        return userAccountMapper.toDto(userAccountRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserAccount resources) {
        UserAccount userAccount = userAccountRepository.findById(resources.getAcctId()).orElseGet(UserAccount::new);
        ValidationUtil.isNull( userAccount.getAcctId(),"UserAccount","id",resources.getAcctId());
        UserAccount userAccount1 = null;
        userAccount1 = userAccountRepository.findByAcctCode(resources.getAcctCode());
        if(userAccount1 != null && !userAccount1.getAcctId().equals(userAccount.getAcctId())){
            throw new EntityExistException(UserAccount.class,"acct_code",resources.getAcctCode());
        }
        userAccount.copy(resources);
        userAccountRepository.save(userAccount);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long acctId : ids) {
            userAccountRepository.deleteById(acctId);
        }
    }

    @Override
    public void download(List<UserAccountDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserAccountDto userAccount : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("账户编码", userAccount.getAcctCode());
            map.put("账户总金额", userAccount.getTotalAmount());
            map.put("可用总金额", userAccount.getUsableAmount());
            map.put("冻结总金额", userAccount.getFrozenAmount());
            map.put("openid", userAccount.getOpenId());
            map.put("系统用户id", userAccount.getSysUserId());
            map.put("金额使用比例", userAccount.getUseRatio());
            map.put("账户类型", userAccount.getAcctType());
            map.put("状态", userAccount.getStatus());
            map.put("可使用开始时间", userAccount.getStartTime());
            map.put("可使用结束时间", userAccount.getEndTime());
            map.put("过期时间", userAccount.getExpireTime());
            map.put("创建时间", userAccount.getCreateTime());
            map.put("更新时间", userAccount.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}